package com.antdesignbackend.backend.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class AuthTokenAspect {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("@annotation(authToken)")
    public void doAuthToken(AuthToken authToken) {
    }

    /**
     * 角色根据role表roleCheckedName进行识别，不根据id
     * keyValue根据users表KeyName进行识别
     * 逻辑说明：
     * 首先必须是登录用户，如果只判断是否登录，使用@AuthToken
     * 如果需要判断登录成功且角色符合要求，使用@AuthToken(role_name = "superAdmin"),多个角色用逗号分割
     * 如果需要判断登录成功，角色或者关键字其中一项符合要求即可，使用@AuthToken(role_name = {"superAdmin",keyValue = "xxxx"})
     *
     * @param pjp
     * @param authToken
     * @return
     * @throws Throwable
     */
    @Around("doAuthToken(authToken)")
    public Object deBefore(ProceedingJoinPoint pjp, AuthToken authToken) throws Throwable {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

//        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        System.out.println("---------方法执行之前-------------");

        //如果未登录，直接跳转登录页面
        Object object = request.getSession().getAttribute("LoginName");
        if (!(object instanceof String)) {
            return "redirect:/login";
        } else {
            boolean b = authToken.checkedMoreVaild();
            if (!b)
                return pjp.proceed();
        }

        //开始判断角色或者关键字是否满足
        String[] roleName = authToken.role_name();//角色数组
        String[] keys = authToken.keyValue();//key匙，针对特定功能仅开放给特定人群使用的

        //处理特定key，key满足允许跳转控制器
        Object sessionKey = request.getSession().getAttribute("Key");
        if (sessionKey != null) {
            if (sessionKey.equals("")) {
                for (String key : keys) {
                    if (sessionKey.equals(key)) return pjp.proceed();
                }
            }
        }
        //角色满足允许跳转
        Object roles = request.getSession().getAttribute("RoleCheckKey");
        if (roles != null) {
            if (!roles.equals("")) {
                String[] split = roles.toString().split(",");
                boolean isChecked = false;
                for (String s : split)

                    if (Arrays.stream(roleName).anyMatch(s::equals)) {
                        isChecked = true;
                        break;//只要一个角色符合预期，就不再循环判断
                    }
                if (isChecked)
                    return pjp.proceed();
                else {
                    return "redirect:/index";
                }
            }
        }

        return pjp.proceed();
    }
}
